package com.bubaiwantong.algorithms1.exchange;

/**
 * @author bubaiwantong
 * @date 2022/12/7 23:54
 * @description this is a class file created by bubaiwantong in 2022/12/7 23:54
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        QuickSort sort = new QuickSort();
        sort.print(arr);
        sort.sort(arr, 0, arr.length - 1);
        sort.print(arr);
    }


    /**
     * 快速排序
     *
     * @param arr
     */
    public void sort(int arr[], int low, int high) {
        if (low >= high) {
            return;
        }
        int mid = partition(arr, low, high);
        sort(arr, low, mid - 1);
        sort(arr, mid + 1, high);
    }

    int partition(int arr[], int begin, int end) {
        int temp = arr[begin];
        int low = begin + 1;
        int high = end;
        while (low <= high) {
            while (low <= high && temp >= arr[low]) {
                low++;
            }

            while (low <= high && temp < arr[high]) {
                high--;
            }

            if (low >= high) {
                break;
            }

            swap(arr, low, high);
        }
        swap(arr, begin, high);
        return high;
    }


    /**
     * 交换
     *
     * @param arr
     * @param i
     * @param j
     */
    public void swap(int arr[], int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /**
     * 输出数组
     *
     * @param arr
     */
    public void print(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

}
